//
//  NearHistoryView.m
//  BusinessMarket
//
//  Created by Michael Li on 2018/12/17.
//  Copyright © 2018年 Michael Li. All rights reserved.
//

#import "NearHistoryView.h"
#import "NearHistoryViewCell.h"
#import "UIView+TYAlertView.h"
#import "HomeModel.h"
#import "ServiceModel.h"
@interface NearHistoryView()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>
@property(nonatomic,strong) UITableView *tableView;
@property(nonatomic,strong) NSMutableArray *demandMuta;
@property(nonatomic,strong) NSMutableArray *servideMuta;
@property(nonatomic,strong) NSDictionary *dict;
//@property(nonatomic,strong) NSMutableArray *historyMuta;
@property(nonatomic,strong) UIView *headView;
@property(nonatomic,assign) NSInteger page;
@property(nonatomic,strong) NSString *urlString;
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@end
static NSString *identifier = @"oneCell";
@implementation NearHistoryView
//-(NSMutableArray *)historyMuta
//{
//    if (!_historyMuta) {
//        NSArray *pathFile = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//        NSString *homeSearchPreference = @"";
//        NSArray *temp = nil;
//        if (self.index == 0) {
//            homeSearchPreference = [pathFile[0] stringByAppendingPathComponent:@"demandThehallHistory.plist"];
//        }else {
//             homeSearchPreference = [pathFile[0] stringByAppendingPathComponent:@"serviceThehallHistory.plist"];
//        }
//        XLog(@"homeSearchPreference:%@",homeSearchPreference);
//        temp = [NSArray arrayWithContentsOfFile:homeSearchPreference];
//        XLog(@"temp:%@",temp);
//        XLog(@"temp.count:%ld",temp.count);
//        if (temp.count) {
//            _historyMuta = [NSMutableArray arrayWithArray:temp];
//        }else {
//            _historyMuta = [NSMutableArray array];
//        }
//
//    }
//    XLog(@"_historyMuta:%ld",_historyMuta.count);
//    return _historyMuta;
//
//}
-(NSMutableArray *)demandMuta
{
    if (!_demandMuta) {
        _demandMuta = [NSMutableArray array];
    }
    return _demandMuta;
}
-(NSMutableArray *)servideMuta
{
    if (!_servideMuta) {
        _servideMuta = [NSMutableArray array];
    }
    return _servideMuta;
}
- (UITableView *)tableView
{
    if (!_tableView) {
        CGRect frame = CGRectMake(-kWidth, -kStatusBarHeight, kWidth/1.5, kHeight+kStatusBarHeight);
        _tableView = [[UITableView alloc] initWithFrame:frame style:UITableViewStylePlain];
        _tableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor whiteColor];
        //        [_menuTabView registerClass:[MenuCell class] forCellReuseIdentifier:identifierMenuCell];
        [_tableView registerNib:[UINib nibWithNibName:@"NearHistoryViewCell" bundle:nil] forCellReuseIdentifier:identifier];
    }
    return _tableView;
}
-(instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = [UIColor colorWithWhite:0.1 alpha:0.8];
        self.manager = [AFHTTPSessionManager manager];
//        self.backgroundColor = kOrangeBg;
//        self.headView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kWidth/1.5, 200)];
//        self.headView.backgroundColor = kOrangeBg;
//        [self addSubview:self.headView];
        [self addSubview:self.tableView];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(shadowViewClick)];
        tap.delegate= self;
        self.page = 1;
        [self addGestureRecognizer:tap];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(historydemandLis:) name:@"historydemandLis" object:nil];
         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(associationhistory:) name:@"associationhistory" object:nil];
         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(qingqiusibai:) name:@"qingqiusibai" object:nil];
//         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteAssociationHistory:) name:@"deleteAssociationHistory" object:nil];
//         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteDemandHistory:) name:@"deleteDemandHistory" object:nil];
    }
    return self;
}
- (void)setIndex:(NSInteger)index
{
    _index = index;
    [WSProgressHUD setProgressHUDIndicatorStyle:WSProgressHUDIndicatorBigGray];
    [WSProgressHUD show];
    if (index == 1) {
        self.demandMuta = nil;
        [self chectHistoryDemand];
    }else {
        self.servideMuta = nil;
        [self chectHistoryService];
    }
}
-(void)qingqiusibai:(NSNotification *)info
{
//    NSDictionary *dict = info.userInfo;
//    XLog(@"dict:%@",dict);
//    NSString *message = [info.userInfo objectForKey:@"message"];
//    [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [WSProgressHUD dismiss];
//    });
}

-(void)chectHistoryDemand
{
    
    self.dict = @{
                  @"uid":[UserDefaultsHelper readUid],
                  @"token": [UserDefaultsHelper readToken]
                  };
    [CustomeManager POSTWithURLIndex:64 parameters:self.dict success:^(NSDictionary *dict) {
        
    } failure:^(NSError *error) {
        
    }];
}
-(void)chectHistoryService
{
    self.dict = @{
                  @"uid":[UserDefaultsHelper readUid],
                  @"token": [UserDefaultsHelper readToken],
                  @"page": [NumberSwitchString numberSwitchString:self.page],
                  @"rows": @"10"
                  };
    XLog(@"self.dict:%@",self.dict);
    [CustomeManager POSTWithURLIndex:66 parameters:self.dict success:^(NSDictionary *dict) {
        
    } failure:^(NSError *error) {
        
    }];
}
#pragma mark-代理:---查询---需求历史记录
-(void)historydemandLis:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    XLog(@"dict:%@",dict);
    NSArray *date = [info.userInfo objectForKey:@"date"];
    for (NSDictionary *dict in date) {
        HomeModel *model = [HomeModel mj_objectWithKeyValues:dict];
        [self.demandMuta addObject:model];
    }
    if (!self.demandMuta.count) {
        self.tableView.emptyDataSetSource = self;
        self.tableView.emptyDataSetDelegate = self;
    }
    [self.tableView reloadData];
    [WSProgressHUD dismiss];
}
//associationhistory
-(void)associationhistory:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    XLog(@"dict:%@",dict);
    NSArray *date = [info.userInfo objectForKey:@"date"];
    for (NSDictionary *dict in date) {
        ServiceModel *model = [ServiceModel mj_objectWithKeyValues:dict];
        [self.servideMuta addObject:model];
    }
    if (!self.servideMuta.count) {
        self.tableView.emptyDataSetSource = self;
        self.tableView.emptyDataSetDelegate = self;
    }

    [self.tableView reloadData];
    [WSProgressHUD dismiss];
}

-(void)deleteAssociationHistory:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
   
}
-(void)deleteDemandHistory:(NSNotification *)info
{
    NSDictionary *dict = info.userInfo;
    XLog(@"dict:%@",dict);
    NSString *message = [info.userInfo objectForKey:@"message"];
    [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [WSProgressHUD dismiss];
    });
}


-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    XLog(@"%@", NSStringFromClass([touch.view class]));
    if ([self.subviews containsObject:self.tableView]) {
        if([touch.view isDescendantOfView:self.tableView]){
            return NO;
        }
        return  YES;
        
    }else {
        return NO;
    }
}
#pragma mark - 点击背景
- (void)shadowViewClick
{
    if ([self.delegate respondsToSelector:@selector(nearHistoryView:withHidden:)]) {
        [self.delegate nearHistoryView:self withHidden:YES];
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.index == 1) {
        return self.demandMuta.count;
    }else {
        return self.servideMuta.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    NearHistoryViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    cell.indexPath = indexPath;
    cell.index = self.index;
    if (self.index == 1) {
        HomeModel *model = self.demandMuta[indexPath.row];
        cell.homeModel = model;
    }else {
        ServiceModel *model = self.servideMuta[indexPath.row];
        cell.servieModel = model;
    }
//    cell.textLabel.text = @"221";
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
//    NSDictionary *dict = [NSDictionary dictionary];
//    NSString *ids = @"";
    if (self.index == 1) {
        HomeModel *model = self.demandMuta[indexPath.row];
//        ids = [NSString stringWithFormat:@"%ld",model.id];
        if ([self.delegate respondsToSelector:@selector(nearHistoryView:withHidden:withIndex:withHomeModel:)]) {
            [self.delegate nearHistoryView:self withHidden:YES withIndex:1 withHomeModel:model];
        }
    }else {
        ServiceModel *model = self.servideMuta[indexPath.row];
//        ids = [NSString stringWithFormat:@"%ld",model.id];
        if ([self.delegate respondsToSelector:@selector(nearHistoryView:withHidden:withIndex:withServiceModel:)]) {
            [self.delegate nearHistoryView:self withHidden:YES withIndex:1 withServiceModel:model];
        }
    }
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *sectionHead = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 80)];
    sectionHead.backgroundColor = kWhite;
    UIImageView *iv = [[UIImageView alloc]initWithFrame:CGRectMake(16, 40, 20, 20)];
    iv.image = [UIImage imageNamed:@"icon_86"];
    [sectionHead addSubview:iv];
    UILabel *label = [[UILabel  alloc]initWithFrame:CGRectMake(CGRectGetMaxX(iv.frame)+10, 40, 100, 20)];
    label.text = @"最近浏览";
    label.textColor = kLabel16Color;
    label.font = [UIFont systemFontOfSize:18];
    [sectionHead addSubview:label];
    UIButton *btn = [[UIButton alloc]initWithFrame:CGRectMake(kWidth/1.5-20-20, 40, 20, 20)];
//    [btn setBackgroundColor:[UIColor blueColor]];
    [btn setImage:[UIImage imageNamed:@"icon_77"] forState:UIControlStateNormal];
    [btn addTarget: self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    [sectionHead addSubview:btn];
//    btn.layer.masksToBounds = YES;
//    btn.layer.cornerRadius = 8;
//    [btn setTitle:@"确定" forState:UIControlStateNormal];
    return sectionHead;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 80;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 0,1)];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}
- (void)setShow:(BOOL)show
{
    _show = show;
    __weak typeof (self)weakSelf = self;
    if (show) {
        [UIView animateWithDuration:0.3 animations:^{
            weakSelf.tableView.transform = CGAffineTransformMakeTranslation(kWidth, 0);
        }];
    }
}
-(void)clickBtn:(UIButton *)clickBtn
{
    clickBtn.selected = !clickBtn.selected;
//    if ([self.delegate respondsToSelector:@selector(nearHistoryView:withHidden:withTag:)]) {
//        [self.delegate nearHistoryView:self withHidden:YES withTag:1];
//    }
    if (clickBtn.selected) {
        [self.tableView setEditing:YES animated:YES];
    }else {
        [self.tableView setEditing:NO animated:YES];
    }
}
-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath

{
    return @"删除";
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
        TYAlertView *alertView = [TYAlertView alertViewWithTitle:@"您确定要删除这个浏览信息吗?" message:@""];
        
        [alertView addAction:[TYAlertAction actionWithTitle:@"取消" style:TYAlertActionStyleCancel handler:^(TYAlertAction *action) {
            
        }]];
    __weak typeof (self)weakSelf = self;
        [alertView addAction:[TYAlertAction actionWithTitle:@"确定" style:TYAlertActionStyleDestructive handler:^(TYAlertAction *action) {
            if (self.index == 1) {
#pragma mark-:删除服务历史记录
                HomeModel *model = self.demandMuta[indexPath.row];
                self.dict = @{
                              @"uid":[UserDefaultsHelper readUid],
                              @"token": [UserDefaultsHelper readToken],
                              @"dids":[NumberSwitchString numberSwitchString:model.id]
                              };
                XLog(@"self.dict:%@",self.dict);
//                [CustomeManager POSTWithURLIndex:67 parameters:self.dict success:^(NSDictionary *dict) {
//                    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
//                } failure:^(NSError *error) {
//
//                }];
                weakSelf.urlString = [NSString stringWithFormat:@"%@/history/deleteDemandHistory",kUrl];
                [weakSelf.manager POST:weakSelf.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    XLog(@"responseObject:%@",responseObject);
                    NSString *message = [responseObject objectForKey:@"message"];
                    [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [WSProgressHUD dismiss];
//                        [weakSelf.demandMuta removeObjectAtIndex:indexPath.row];
                        [weakSelf.demandMuta removeObject:model];
//                        [weakSelf.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
                        [weakSelf.tableView reloadData];
                    });
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    
                }];
            }else {
                #pragma mark-:删除服务历史记录
                ServiceModel *model = self.servideMuta[indexPath.row];
                self.dict = @{
                              @"uid":[UserDefaultsHelper readUid],
                              @"token": [UserDefaultsHelper readToken],
                              @"aids":[NumberSwitchString numberSwitchString:model.id]
                              };
                XLog(@"self.dict:%@",self.dict);
//                [CustomeManager POSTWithURLIndex:68 parameters:self.dict success:^(NSDictionary *dict) {
//                     [weakSelf.servideMuta removeObject:model];
//                    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
//                } failure:^(NSError *error) {
//
//                }];
                weakSelf.urlString = [NSString stringWithFormat:@"%@/history/deleteAssociationHistory",kUrl];
                [weakSelf.manager POST:weakSelf.urlString parameters:self.dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                    XLog(@"responseObject:%@",responseObject);
                    NSString *message = [responseObject objectForKey:@"message"];
                    [WSProgressHUD showImage:[UIImage imageNamed:@""] status:message];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [WSProgressHUD dismiss];
                        [weakSelf.servideMuta removeObject:model];
                        [weakSelf.tableView reloadData];
                    });
                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                    
                }];
            }
            
        }]];
        [alertView showInWindowWithOriginY:200 backgoundTapDismissEnable:YES];
}
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    UIImage *image = [UIImage imageNamed:@"empty"];
    return image;
}
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = [NSBundle bundleLocalizedStringForKey:@"noData"];
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[UIFont boldSystemFontOfSize:14],
                                 NSForegroundColorAttributeName:kLabel102Color
                                 };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}
@end
